package controller

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"time"
)

type line struct {
	db *gorm.DB
}

var Line = line{}

var Db *gorm.DB

type PointShip struct {
	//	northid int lon float64 lat float64 ct string spd float64 hdg float64 cog float64
	Northid string    `json:"northid" gorm:"column:northid"`
	Lon     float64   `json:"lon" gorm:"column:lon"`
	Lat     float64   `json:"lat" gorm:"column:lat"`
	Ct      time.Time `json:"ct" gorm:"column:ct"`
	Spd     float64   `json:"spd" gorm:"column:spd"`
	Hdg     float64   `json:"hdg" gorm:"column:hdg"`
	Cog     float64   `json:"cog" gorm:"column:cog"`
}

// GetLineData
func (ctl *line) GetLineData(c *gin.Context) {
	ctl.db = Db
	northid := c.Query("northid")
	ctStartStr := c.Query("ctStart")
	ctEndStr := c.Query("ctEnd")
	fmt.Println(northid, ctStartStr, ctEndStr)
	// 尝试将时间字符串转换为 time.Time 类型
	//ctStart, err := time.Parse("2006-01-02 15:04:05", ctStartStr)
	//if err != nil {
	//	c.JSON(400, gin.H{
	//		"code": 400,
	//		"msg":  "Invalid ctStart format. Expected 'YYYY-MM-DD HH:MM:SS'",
	//		"data": nil,
	//	})
	//	return
	//}
	//ctEnd, err := time.Parse("2006-01-02 15:04:05", ctEndStr)
	//if err != nil {
	//	c.JSON(400, gin.H{
	//		"code": 400,
	//		"msg":  "Invalid ctEnd format. Expected 'YYYY-MM-DD HH:MM:SS'",
	//		"data": nil,
	//	})
	//	return
	//}

	//fmt.Println(northid, ctStart, ctEnd, ctl.db)
	var point []PointShip
	// 获取时间范围内，northid 匹配的数据
	result := ctl.db.Where("northid = ? AND ct >= ? AND ct <= ?", northid, ctStartStr, ctEndStr).
		Find(&point)
	if result.Error != nil {
		fmt.Println(6666)
		c.JSON(500, gin.H{
			"code": 500,
			"msg":  "Database query error: " + result.Error.Error(),
			"data": nil,
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "success",
		"data": point,
	})
}

// 获取所有的northid
func (ctl *line) GetNorthid(c *gin.Context) {
	ctl.db = Db
	var northid []string
	result := ctl.db.Table("point_ship").Select("distinct(northid)").Find(&northid)
	if result.Error != nil {
		c.JSON(500, gin.H{
			"code": 500,
			"msg":  "Database query error: " + result.Error.Error(),
			"data": nil,
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "success",
		"data": northid,
	})
}
